import "KaiUI/src/views/ListView/ListView.scss";
import { Component } from "inferno";
import { findDOMNode } from "inferno-extras";

class ListView extends Component {
  handleKeyDown = (evt) => {
    let cursor = this.state.cursor;
    this.children[cursor].props.isFocused = false;
    if (evt.key === "ArrowUp") {
      cursor--;
      if (cursor === -1) cursor = this.children.length - 1;
      if (this.children[cursor].props.unFocusable) cursor--;
      if (cursor === -1) cursor = this.children.length - 1;
      // TODO: summarize all of these three "if"s
    } else if (evt.key === "ArrowDown") {
      cursor++;
      if (cursor === this.children.length) cursor = 0;
      if (this.children[cursor].props.unFocusable) cursor++;
      if (cursor === this.children.length) cursor = 0;
      // TODO: same as above! ME LAZY Farooq
    }
    this.children[cursor].props.isFocused = true;
    findDOMNode(this.children[cursor]).scrollIntoView();
    console.log(`[ListView] cursor is set on ${cursor}`);
    this.setState({
      cursor: cursor,
    });
    this.cursorChangeCb && this.cursorChangeCb(cursor);
  };

  resetChildrenCursor = (children) => {
    this.children = children;
    this.children[0].props.isFocused = true;
    this.setState({ cursor: 0 });
  };
  constructor(props) {
    super(props);
    const { cursor, children, cursorChangeCb } = props;
    if (cursor - 1 > children.length || cursor < 0) {
      console.error(
        `[ListView] cursor should be from 0 to ${
          children.length - 1
        } but is ${cursor}`
      );
      throw new Error("cursor is negative or bigger than length of list");
    }
    if (children instanceof Array) {
      this.children = children;
    } else {
      this.children = [children];
    }
    this.children[cursor].props.isFocused = true;
    this.cursorChangeCb = cursorChangeCb;
    if (cursorChangeCb) cursorChangeCb(cursor);
    this.state = {
      cursor: cursor,
    };
  }

  componentDidMount() {
    document.addEventListener("keydown", this.handleKeyDown);
  }

  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleKeyDown);
  }

  render() {
    return <div className={"kai-list-view"}>{this.children}</div>;
  }
}

export default ListView;
